<template>
  <div class="login-container">
    <van-nav-bar title="登录">
      <template #left>
        <img class="logo" src="@/assets/images/logo.png"/>
      </template>
    </van-nav-bar>
 <van-form @submit="onSubmit">
      <van-field
        v-model="formLogin.mobile"
        type="tel"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="[{ required: true, message: '请填写手机号', trigger: 'onChange'},
        {pattern: /^1[3-9]\d{9}$/, message: '请正确手机号', trigger: 'onChange' }]"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        label="密码"
        placeholder="请输入验证码"
        required
        :rules="[{ required: true, message: '请填写验证码', trigger: 'onChange' },
        {pattern: /^\d{6}$/ , message: '请正确验证码', trigger: 'onChange'}]"
      />
      <div style="margin: 16px;">
        <!-- :loading='loading' 是否开启加载 -->
        <!-- loading-type='spinner' 加载的样式 -->
        <!-- loading-text="登陆中..." 加载的文字效果 -->
        <van-button block type="info" native-type="submit" :loading='loading'  loading-type='spinner' loading-text="登陆中..." >登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>

import { loginAPI } from '@/api/login'
import { mapMutations } from 'vuex'
import { Notify } from 'vant'
export default {
  name: 'Login',
  data () {
    return {
      // 初始化表单的值
      formLogin: {
        mobile: '13888888888',
        code: '246810' // 默认只能用246810后台规定了
      },
      // 登陆加载状态默认不加载
      loading: false
    }
  },
  methods: {
    ...mapMutations('user', ['setToken', 'setRefreshToken']),
    // 登陆后发送请求
    async onSubmit () {
      try {
      // ...
      // 登陆成功前不显示加载状态
        this.loading = true
        // 调用接口
        const res = await loginAPI({
          tel: this.formLogin.mobile,
          pwd: this.formLogin.code
        })
        // 登陆成功后不显示加载状态
        this.loading = false
        // 获取token和refreshToken
        // console.log(res)
        // 解构赋值
        const { token, refresh_token: RefreshToken } = res.data.data
        // 赋值给mutations
        this.setToken(token)
        this.setRefreshToken(RefreshToken)

        // 登陆成功后跳转路由到home界面
        // replace  不可回退
        this.$router.replace({
          path: '/layout'
        })

        Notify({ type: 'success', message: '登录成功' })
      } catch (err) {
        Notify({ type: 'warning', message: '手机号或密码错误' })
        // 登陆成功后不显示加载状态
        this.loading = false
      }
    }

  }
}
</script>

<style lang="less" scoped>
.logo {
  width: 100px;
  height: 30px;
}
</style>
